package com.example.test19_4;

import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private LocalBroadcastManager localBroadcastManager;
    private LocalBroadcasttest localBroadcasttest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        localBroadcastManager = LocalBroadcastManager.getInstance(MainActivity.this);
        localBroadcasttest = new LocalBroadcasttest();
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setAction("com.example.test19_4.MY_LOCALBROADCAST");
                localBroadcastManager.sendBroadcast(intent);
            }
        });
        //动态注册广播接受者
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.test19_4.MY_LOCALBROADCAST");
        localBroadcastManager.registerReceiver(localBroadcasttest,intentFilter);
    }
    private class LocalBroadcasttest extends BroadcastReceiver{
        @Override
        public void onReceive(Context context,Intent intent){
            Toast.makeText(MainActivity.this,"这是一个本地广播",Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    protected void onDestroy(){
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(localBroadcasttest);
    }
}